/*
 * Copyright (C) 2025 Huawei Device Co., Ltd.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#ifndef NODE_HTTP2_HANDLE_SHAKE_H
#define NODE_HTTP2_HANDLE_SHAKE_H

#include "napi/http2_constant.h"
#include "nghttp2/nghttp2.h"
#include "ohos_log.h"
#include "openssl/err.h"
#include "openssl/ossl_typ.h"
#include "openssl/ssl.h"
#include "openssl/tls1.h"
#include <fcntl.h>
#include <netinet/in.h>
#include <string>
#include <netinet/tcp.h>
#include <map>
#include <poll.h>
#include <cstdio>
#include <netdb.h>
#include <unistd.h>
#include <nghttp2/nghttp2.h>
#include <fcntl.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/conf.h>
#include <unordered_map>
#include "ohos_log.h"
#include "http2_struct.h"
#include "napi/native_api.h"
#include "http2_constant.h"
#include "http2_map.h"
#include "utils/napi/napi_utils.h"
#include <uv.h>
#include "napi/http2_utils.h"

int SelectNextProtoCb(SSL *ssl, unsigned char **out, unsigned char *outlen, const unsigned char *in,
                      unsigned int inlen, void *arg)
{
    int rv = 0;
    rv = nghttp2_select_next_protocol(out, outlen, in, inlen);
    if (rv <= 0) {
        LOGE("Server did not advertise HTTP/2 protocol");
    }
    return SSL_TLSEXT_ERR_OK;
}

void InitSslCtx(SSL_CTX *sslCtx)
{
    SSL_CTX_set_options(sslCtx, SSL_OP_ALL | SSL_OP_NO_SSLv2);
    SSL_CTX_set_mode(sslCtx, SSL_MODE_AUTO_RETRY);
    SSL_CTX_set_mode(sslCtx, SSL_MODE_RELEASE_BUFFERS);
    SSL_CTX_set_next_proto_select_cb(sslCtx, SelectNextProtoCb, nullptr);
    std::string alpnProtos = "\x02h2";
    const unsigned char* protos = reinterpret_cast<const unsigned char*>(alpnProtos.c_str());
    SSL_CTX_set_alpn_protos(sslCtx, protos, NUM_3);
}

int OpenSSLConnectHandle(SSL *ssl, int fd, std::string host)
{
    std::size_t hostLen = host.find(':');
    std::string domainName = host.substr(0, hostLen);
    LOGE("ssl_handshake host %s domain %s fd %d", host.c_str(), domainName.c_str(), fd);
    int rv = 0;
    if (SSL_set_fd(ssl, fd) == 0) {
        LOGE("SSL_set_fd %s", ERR_error_string(ERR_get_error(), nullptr));
    }
    ERR_clear_error();
    SSL_ctrl(ssl, SSL_CTRL_SET_TLSEXT_HOSTNAME, TLSEXT_NAMETYPE_host_name,
             static_cast<void*>(const_cast<char*>(domainName.c_str())));
    rv = SSL_connect(ssl);
    if (rv <= 0) {
        LOGE("SSL_connect %s", ERR_error_string(ERR_get_error(), nullptr));
    }
    return rv;
}

void MakeNonBlock(int fd)
{
    int flags;
    int rv;
    while ((flags = fcntl(fd, F_GETFL, 0)) == -1 && errno == EINTR) {
        if (flags == -1) {
            LOGE("fcntl %s", strerror(errno));
        }
    }
    while ((rv = fcntl(fd, F_SETFL, flags | O_NONBLOCK)) == -1 && errno == EINTR) {
        if (rv == -1) {
            LOGE("fcntl end %s", strerror(errno));
        }
    }
}

void SetTcpNodelay(int fd)
{
    int val = 1;
    int rv = 0;
    rv = setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, static_cast<socklen_t>(sizeof(val)));
    if (rv == -1) {
        LOGE("setsockopt %s", strerror(errno));
    }
}

bool IsDestroyed(int fd)
{
    bool result = false;
    auto it = g_sessionManagerMap.find(fd);
    if (it != g_sessionManagerMap.end()) {
        for (const auto &child : g_sessionManagerMap) {
            if ((child.first == fd) && (child.second == 1)) {
                result = true;
                break;
            }
        }
    }
    return result;
}

#endif //NODE_HTTP2_HANDLE_SHAKE_H
